
#include <wiisprite.h>


#include "Entity.h"
#include "Creature.h"

using namespace wsp;
using namespace std;


Creature::Creature()
    :sprite(),
	ticker(0), frameWait(15), moving(false)/*,
	currentDir(DIR_DOWN), 
	lastDir(DIR_UP)*/ // Last so that is has to do a trasition right away.
	// No longer needed with new change to only change direction when needed, 
	// caused rotation at beginning if left in.
{
	layer=(&sprite);
}



Creature::~Creature()
{
	/* As sprite is going out of scope, layer will point to freed memory. 
	 * Not sure about this one.
	 */
	layer = NULL; 
}

bool Creature::Update()
{
	/*if(lastDir != currentDir){
		Face(currentDir);		
	}*/
	ticker++;
	
	if(moving && ticker >= frameWait){
		sprite.NextFrame();
		ticker = 0;
	}
	else if(!moving) {
		sprite.SetFrame(0);
	}
	
	return true;
}

void Creature::OnHit()
{
	// No nothing yet
}


Sprite Creature::GetSprite() {
	return sprite;
}

void Creature::SetSprite(Sprite spr){
	sprite = spr;  // Layer already points to sprite, no need to set it again.
}

void Creature::SetImage(Image * img, u32 tileWidth, u32 tileHeight)
{
	sprite.SetImage(img, tileWidth, tileHeight);
}

const Image* Creature::GetImage() const {
	return sprite.GetImage();
}



//  Layer stuff
void Creature::SetPosition(f32 x, f32 y){
	sprite.SetPosition(x,y);
}

void Creature::MovePosition(f32 x, f32 y) {
	//moving = (x || y);
	sprite.Move(x,y);
}

void Creature::SetSequences(std::vector<u32> seq[], u32 size)
{
	for (u32 i=0; i < size; i++){
		sequences[i]=seq[i];
	}
}

void Creature::SetSequences(vector<u32> left, vector<u32> up,
					vector<u32> down, vector<u32>right)
{
	sequences[DIR_LEFT] = left;
	sequences[DIR_UP] = up;
	sequences[DIR_DOWN] = down;
	sequences[DIR_RIGHT] = right;
}

void Creature::SetSequences(u32 left[], u32 sLeft, u32 up[], u32 sUp,
					u32 down[], u32 sDown, u32 right[], u32 sRight)
{
	sequences[DIR_LEFT] = vector<u32>(left, left+sLeft);
	sequences[DIR_UP] = vector<u32>(up, up+sUp);
	sequences[DIR_DOWN] = vector<u32>(down, down+sDown);
	sequences[DIR_RIGHT] = vector<u32>(right, right+sRight);

}

void Creature::SetFrameWait(u32 wait){
	frameWait = wait;
}

void Creature::Face(Direction dir){
	if(currentDir != dir) {
		lastDir = currentDir;
		currentDir = dir;
		if(sequences[dir].size()){
			sprite.SetFrameSequence(&(sequences[dir][0]), sequences[dir].size());
		}
		ticker = frameWait-1;  // Will change frames as soon as a direction is pressed.
	}
}